package com.fintech.pangu.elasticsearch.service.impl;

import com.fintech.pangu.elasticsearch.service.AnalyzeService;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.admin.indices.analyze.AnalyzeResponse;
import org.elasticsearch.client.IndicesAdminClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分析查询服务实现类
 *
 * @author xujunqi
 * @author chendongdong
 * @date 2019/3/14 13:12
 */
public class AnalyzeServiceImpl implements AnalyzeService {
    private final static Logger logger = LoggerFactory.getLogger(AnalyzeServiceImpl.class);

    private IndicesAdminClient indicesAdminClient;

    public AnalyzeServiceImpl() {
    }

    public AnalyzeServiceImpl(IndicesAdminClient indicesAdminClient) {
        this.indicesAdminClient = indicesAdminClient;
    }

    public AnalyzeServiceImpl indicesAdminClient(IndicesAdminClient indicesAdminClient) {
        this.indicesAdminClient = indicesAdminClient;
        return this;
    }

    /**
     * 分词查询服务
     *
     * @param text     分词文本
     * @param analyzer 分词器名称
     **/
    @Override
    public List<String> queryAnalyzer(String text, String analyzer) {
        Assert.hasText(text, "分词文本[text]不能为空");
        Assert.hasText(analyzer, "分词器名称[analyzer]不能为空");
        List<String> termList = new ArrayList<>();
        try {
            AnalyzeResponse response = indicesAdminClient.prepareAnalyze(text).setAnalyzer(analyzer).get();
            if (response != null && CollectionUtils.isNotEmpty(response.getTokens())) {
                termList = response.getTokens().stream().map(AnalyzeResponse.AnalyzeToken::getTerm).collect(Collectors.toList());
            }
        } catch (Exception e) {
            logger.error("查询分词器异常", e);
        }
        return termList;
    }
}
